package com.wecon.springdemo.shiro;

import com.wecon.springdemo.bean.User;
import com.wecon.springdemo.bean.UserExample;
import com.wecon.springdemo.mapper.UserMapper;
import com.wecon.springdemo.service.ManagerUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Weikang  Wang
 * @program: com.wecon.springdemo.shiro
 * @description: 自定义Realm
 * @date 2020/4/28 12:03
 */
public class UserRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    private ManagerUserService managerUserService;

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("执行授权逻辑...principals:{}", principals);
        // 获取用户登录名
        String username = SecurityUtils.getSubject().getPrincipal().toString();
        User userByName = managerUserService.getUserByName(username);
        List<String> roleList = new ArrayList<>();
        List<String> permissionList = new ArrayList<>();

        // 添加资源的授权字符串
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("add");
//        info.addRole("admin");

        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("执行认证逻辑...token:{}", token);

        // 1.判断用户名
        String tokenUser = token.getPrincipal().toString();
//        User userByName = managerUserService.getUserByName(tokenUser);
        User userByName = new User();
        userByName.setId(1);
        userByName.setTelphone("13512345678");
        userByName.setPassword("root");
        userByName.setNickName("David");
        userByName.setGender(1);

        logger.info("userName:{}, userPsw:{}", userByName.getNickName(), userByName.getPassword());

        if (userByName == null) {
            return null;
        }

        if (!tokenUser.equals(userByName.getNickName())) {
            // 返回null，shiro底层会给UnKnowAccountException异常
            return null;
        }

        // 2.密码判断(第二位一定是数据库的密码)
        return new SimpleAuthenticationInfo("", userByName.getPassword(), "");
    }
}
